dofile (getScriptPath() .. "\\..\\processor\\processor.lua")
dofile (getScriptPath() .. "\\..\\processor\\watchdog.lua")
dofile (getScriptPath() .. "\\..\\processor\\log.lua")
dofile (getScriptPath() .. "\\..\\processor\\notify.lua")

dofile (getScriptPath() .. "\\..\\lib\\actions.lua")
dofile (getScriptPath() .. "\\..\\lib\\lib.lua")
dofile (getScriptPath() .. "\\..\\lib\\orders.lua")

script_name = string.gsub(string.gsub(debug.getinfo(1).short_src, "%.[^%.]*$", ""), "^.*[\\/]", "")

daily_exit = {
	done = {}
}

processor:AddInit(function()
	client_code = lib:GetUser()
    if not client_code then return true end
	script_id = client_code .. "#" .. script_name
	log_file = lib.path.log .. script_id .. ".log"
end)

processor:AddInit(function()
	processor:InitLog(log_file)
	processor:InitWatchdog(script_id)
end)

processor:AddInit(function()
	processor:log("started")
end)

processor:AddTimer(function(t)
	if not lib:isConnected() then return true end
	
	local first, last
	local positions = orders:GetPosition()
	local today, day = lib:FormatDate()
	--message(lib:toline(positions))
	for sec_code, position in pairs(positions) do
		if daily_exit.done[sec_code] ~= today then
			first, last = lib:GetInstrumentTradeTime(sec_code)
			if last then
				last = lib:tickseconds(last) - math.random(360, 600)
				if last <= lib:tickseconds() then
					daily_exit:Exit(sec_code, day)
					daily_exit.done[sec_code] = today
				end
			end
		end
	end
end)


function daily_exit:Exit(instrument, day)
	if type(instrument) == "string" then
		instrument = lib:GetInstrument(instrument)
		if not instrument then return end
	end
	
	local wday = day.wday or day.week_day
	
	if wday >= 2 and wday <= 5 then		-- mon - thu
		if instrument then
			processor:notify("HALF " .. instrument.code)
		else
			processor:notify("HALF")
		end
		
		actions:Half(instrument)
	else								-- friday
		if instrument then
			processor:notify("EXIT " .. instrument.code)
		else
			processor:notify("QUIT")
		end
		
		actions:Exit(instrument)
	end
end


